# coding: utf-8

from datetime import date, timedelta

from flask import request
from flask_restful import Api

from app.api.codes import PARAMS_ILLEGAL
from app.api.supplier_codes import (
    SUP_ALREADY_AUTH, NOT_ENGINEER, REDEEM_NOT_EXISTED,
    REDEEM_INACTIVE, REDEEM_USED
)
from app.api.supplier_schemas import redeem_code_schema
from app.api_v2.user_schemas import user_info_schema
from app.api_v2.supplier_schemas import supplier_certify_schema
from app.api_v2.utils import ip_to_area
from app.api_v2.views import AppAuthResource, Response
from app.op.constant import (
    UserStatus, UserType, UserLevel, UserActive
)
from app.op.models import UserTag, RedeemCode, Voucher
from common.constant import RedeemStatus, RedeemGiftType, GiveVoucherReason

api = Api()


@api.resource('/supplier/certify')
class AppSupplierCertifyResource(AppAuthResource):
    """
    create by ld_wu 2017-11-20
    工程商认证
    """

    def post(self):
        if self.user.status == UserStatus.PASS.value:
            return Response(SUP_ALREADY_AUTH)

        data, errors = supplier_certify_schema.load(request.get_json())
        if errors:
            return Response(
                PARAMS_ILLEGAL.new_format_msg(list(errors.values())[0][0]))

        self.user.type = UserType.ENGINEER.value
        self.user.level = UserLevel.LEVEL_2.value
        self.user.status = UserStatus.PENDING.value
        self.user.active = UserActive.ACTIVE.value

        # 更新用户信息
        self.user.nickname = data['nickname']
        self.user.gender = data['gender']
        self.user.com = data.get('com') or self.user.com
        if not self.user.area_id:
            prov, city = ip_to_area(request.remote_addr)
            self.user.city = city.name
            self.user.prov = prov.name
            self.user.area_id = city.id

        # 写入默认标签
        UserTag.default_tag(self.user.id)

        # 若没有套餐, 表示是初次绑定, 赠送套餐
        if not self.user.pack:
            self.user.gift_bid_point()

        user_info = user_info_schema.dump(self.user)[0]

        return Response(body=dict(user=user_info))


@api.resource('/supplier/redeem_code')
class SupplierRedeemCodeResource(AppAuthResource):
    """
    created by chenhj at 2018/9/25
    工程商使用兑换码
    """

    def post(self):
        """
        created by chenhj at 2018/9/25

        """
        # 不是工程商则直接返回
        if self.user.type != UserType.ENGINEER.value:
            return Response(NOT_ENGINEER)

        data, errors = redeem_code_schema.load(request.get_json())
        if errors:
            return Response(PARAMS_ILLEGAL.new_format_msg(list(errors.values())[0][0]))

        redeem_code = RedeemCode.get_by_args(code=data['code'])
        if not redeem_code:
            return Response(REDEEM_NOT_EXISTED)

        if redeem_code.status == RedeemStatus.INACTIVE.value:
            return Response(REDEEM_INACTIVE)

        if redeem_code.redeem_expired_date < date.today():
            redeem_code.status = RedeemStatus.INACTIVE.value
            return Response(REDEEM_INACTIVE)

        if redeem_code.status == RedeemStatus.USED.value:
            return Response(REDEEM_USED)

        if redeem_code.gift_type == RedeemGiftType.VOUCHER.value:
            gift_cnt = redeem_code.count
            code = redeem_code.code
            gift_days = redeem_code.gift_days
            gift_amount = redeem_code.gift_amount

            expired_date = date.today() + timedelta(days=gift_days)
            for _ in range(gift_cnt):
                Voucher.create(
                    user_id=self.user.id,
                    bid_point=gift_amount,
                    reason=GiveVoucherReason.MARKETING.value,
                    redeem_code=code,
                    expired_date=expired_date
                )

        redeem_code.status = RedeemStatus.USED.value
        redeem_code.user_id = self.user.id
        redeem_code.redeem_date = date.today()
        return Response()
